package com.lanzuo.yxd.scanner.scanner.event;

import cn.hutool.extra.spring.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;

import java.util.Arrays;
import java.util.List;

@Slf4j
public class PanelEventPublishUtil {

    /**
     * 私有构造函数，防止外部 new
     */
    private PanelEventPublishUtil() {
        //  初始化资源
    }

    /**
     * 提供全局访问点
     */
    public static PanelEventPublishUtil getInstance() {
        return Holder.INSTANCE;
    }

    /**
     * panel 事件信息推送
     *
     * @param message 消息 -> SN;SN;SN;SN
     */
    public static void publishPanelMessage(String message, Integer lane, String scannerIp, String scannerPosition) {
        // 处理数据, 特殊字符删除
        message = message.replace("\n", "").replace("\r", "");
        List<String> panels = Arrays.asList(message.split(";"));

        getInstance().publish(panels, lane, scannerIp, scannerPosition);
    }

    /**
     * 具体事件推送方法
     *
     * @param panels all panels.
     */
    private void publish(List<String> panels, Integer lane, String scannerIp, String scannerPosition) {
        ApplicationEventPublisher eventPublisher = SpringUtil.getBean(ApplicationEventPublisher.class);
        eventPublisher.publishEvent(new MessageReceiveEvent(this, panels, lane, scannerIp, scannerPosition));
        log.info("已发送事件, 消息：{}", panels);
    }

    /**
     * 私有静态内部类实现懒加载单例 线程安全
     */
    private static class Holder {
        private static final PanelEventPublishUtil INSTANCE = new PanelEventPublishUtil();
    }

}
